package com.zerone.dy.demomsg.webSocket.service;

import com.alibaba.fastjson.JSON;
import com.zerone.dy.demomsg.entity.Message;
import com.zerone.dy.demomsg.eum.MessageType;
import com.zerone.dy.demomsg.excpetion.JbMessageExcpetion;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import javax.websocket.Session;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;


@Slf4j
public class WebSocketSessionService {

    public static Map<String, Session> sessionMap = new ConcurrentHashMap<>();


    private static void vaildMessage(Message message) throws JbMessageExcpetion {
        if(message==null){
            log.error("发送消息失败:message为空");
            throw new JbMessageExcpetion("发送消息失败:message为空");
        }
        if(!MessageType.isExist(message.getIsGroup())){
            log.error("发送消息失败:message.getIsGroup()不合法");
            throw new JbMessageExcpetion("发送消息失败:message.getIsGroup()不合法");
        }
        if(StringUtils.isBlank(message.getTo())){
            log.error("发送消息失败:message.getTo()不合法");
            throw new JbMessageExcpetion("发送消息失败:message.getTo()不合法");
        }
    }

    public static void sendMsg(Message message) throws JbMessageExcpetion {
        vaildMessage(message);
        if(message.getIsGroup()==1){
            sendMsgToUser(message);
        } else if (message.getIsGroup()==2) {
            sendMsgToGroup(message);
        }
    }


    private static void sendMsgToUser(Message message) throws JbMessageExcpetion {
        Session session = sessionMap.get(message.getTo());
        if(session==null){
            log.error("发送消息失败:session为空");
            return;
        }
        session.getAsyncRemote().sendText(JSON.toJSONString(message));
    }

    private static void sendMsgToGroup(Message message) throws JbMessageExcpetion {

    }

    public static void removeSession(String userId){
        if(sessionMap.containsKey(userId)){
            sessionMap.remove(userId);
        }
    }

    public static void addSession(String userId,Session session){
        sessionMap.put(userId,session);
    }

}
